package com.oceansoft.mobile.pool;

import org.apache.commons.net.ftp.FTPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.*;

/**
 * Created by lenovo on 2017/7/21.
 */
@Controller
@RequestMapping("api/ftp")
public class FTPClientTest {
    private FTPClient ftpClient;

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @ResponseBody
    @RequestMapping(value = "test")
    public void test() throws Exception {
        FTPClientConfig config = new FTPClientConfig();
        config.setHost("172.16.1.205");
        config.setPort(21);
        config.setUsername("test");
        config.setPassword("szgawx");
        config.setEncoding("utf-8");
        config.setPassiveMode("false");
        config.setClientTimeout(30 * 1000);

        FTPClientFactory factory = new FTPClientFactory(config);
        FTPClientPool pool = new FTPClientPool(factory);
        ftpClient = pool.borrowObject();
        uploadFile(new File("d:/detail/54.html"), "/ftp/");
    }


    /***
     * 上传Ftp文件
     * @param localFile 当地文件
     * @param romotUpLoadePath 上传服务器路径 - 应该以/结束
     * */
    public boolean uploadFile(File localFile, String romotUpLoadePath) {
        InputStream inStream = null;
        boolean success = false;
        String txt="320681199309283229";
        try {
            this.ftpClient.changeWorkingDirectory(romotUpLoadePath);// 改变工作路径
           // inStream = new BufferedInputStream(new FileInputStream(localFile));
            inStream =new ByteArrayInputStream(txt.getBytes());
            log.info(localFile.getName() + "开始上传.....");
            success = this.ftpClient.storeFile("test.txt", inStream);
            if (success == true) {
                log.info(localFile.getName() + "上传成功");
                return success;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            log.error(localFile + "未找到");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return success;
    }
}
